package com.wongoing.util;

import java.util.Collection;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.ResourceBundle;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.alibaba.fastjson.JSONObject;

import cn.jiguang.common.resp.APIConnectionException;
import cn.jiguang.common.resp.APIRequestException;
import cn.jsms.api.SendSMSResult;
import cn.jsms.api.ValidSMSResult;
import cn.jsms.api.common.SMSClient;
import cn.jsms.api.common.model.SMSPayload;
import com.wongoing.bus.util.Constants;
import com.wongoing.util.manager.SmsVerCodeManager;
import com.wongoing.util.manager.SmsVerCodeManagerBean;

public class JsmsUtil {

	protected static final Logger LOG = LoggerFactory.getLogger(JsmsUtil.class);
	private static final ResourceBundle bundle = java.util.ResourceBundle.getBundle("config");
	/*private static final String APPKEY = bundle.getString("appKey");
	private static final String MASTERSECRET = bundle.getString("masterSecret");*/
	private static final String APPKEY = Constants.JPUSH_APPKEY;
	private static final String MASTERSECRET = Constants.JPUSH_MASTERSECRET;
	
	    public static Map<String,Object> SendSMSCode(String mobile) {
    	SMSClient client = new SMSClient(MASTERSECRET, APPKEY);
    	SMSPayload payload = SMSPayload.newBuilder()
				.setMobildNumber(mobile)
				.setTempId(1)//20186
				.build();
    	try {
    		//清理过期与跨天数据
    		clear();
    		//检测未过期短信缓存中是否有本手机号的信息，如果有则更改信息(为保证数据正确性，重新进行数据的循环)
    		SmsVerCodeManagerBean smsBean = null; 
    		for (SmsVerCodeManagerBean bean : SmsVerCodeManager.getInstance().getAllVerCode()) {
    			if(bean.getMobile().equals(mobile)) {
    				smsBean = bean;
    			}
			}
    		//不存在则new一个新类
    		if(null==smsBean) {
    			smsBean = new SmsVerCodeManagerBean(); 
    		}
    		//检测是否达到了每天最大发送是数量
			if(smsBean.getSendCount()>smsBean.getSendMaxCount()) {
				//不可再发送，给前台提示已到当日最大发送限制
				return smsResultMap(false,"您已超过当日短信发送的最大限制");
			}
    		SendSMSResult res = client.sendSMSCode(payload);
			String msgId = JSONObject.parseObject(res.toString()).getString("msg_id"); 
			smsBean.setMobile(mobile);
			smsBean.setMsgId(msgId);
			smsBean.setSendCount(smsBean.getSendCount()+1);
			smsBean.setSendDateTime(DateConvert.formatDateToString(new Date(), DateStyle.YYYY_MM_DD_HH_MM_SS));
			SmsVerCodeManager.getInstance().addVerCode(mobile, smsBean);
			return smsResultMap(true,msgId);
		} catch (APIConnectionException e) {
            LOG.error("网络连接失败，请稍后再试! ", e);
            return smsResultMap(false,"网络连接失败，请稍后再试! ");
        } catch (APIRequestException e) {
            LOG.error("极光服务器相应错误，请查看并修复! ", e);
            LOG.info("HTTP状态: " + e.getStatus());
            LOG.info("Error消息: " + e.getMessage());
            return smsResultMap(false,"服务器相应错误，请查看并修复! ");
        } catch(Exception e ) {
            return smsResultMap(false,"未知异常! ");
        }
    }
    
    /**
     * 功能说明：发送注册短信
     * 修改说明：
     * @author 吴兆强
     * @date 2018年1月25日 下午1:53:34
     * @param mobile
     * @return
     */
    public static Map<String,Object> SendSMSRegisterCode(String mobile) {
    	SMSClient client = new SMSClient(MASTERSECRET, APPKEY);
    	SMSPayload payload = SMSPayload.newBuilder().setMobildNumber(mobile).setTempId(1).build();
    	try {
    		//清理过期与跨天数据
    		clear();
    		//检测未过期短信缓存中是否有本手机号的信息，如果有则更改信息(为保证数据正确性，重新进行数据的循环)
    		SmsVerCodeManagerBean smsBean = null; 
    		for (SmsVerCodeManagerBean bean : SmsVerCodeManager.getInstance().getAllVerCode()) {
    			if(bean.getMobile().equals(mobile)) {
    				smsBean = bean;
    			}
			}
    		//不存在则new一个新类
    		if(null==smsBean) {
    			smsBean = new SmsVerCodeManagerBean(); 
    		}
    		//检测是否达到了每天最大发送是数量
			if(smsBean.getSendCount()>smsBean.getSendMaxCount()) {
				//不可再发送，给前台提示已到当日最大发送限制
				return smsResultMap(false,"您已超过当日短信发送的最大限制");
			}
    		SendSMSResult res = client.sendSMSCode(payload);
			String msgId = JSONObject.parseObject(res.toString()).getString("msg_id"); 
			smsBean.setMobile(mobile);
			smsBean.setMsgId(msgId);
			smsBean.setSendCount(smsBean.getSendCount()+1);
			smsBean.setSendDateTime(DateConvert.formatDateToString(new Date(), DateStyle.YYYY_MM_DD_HH_MM_SS));
			SmsVerCodeManager.getInstance().addVerCode(mobile, smsBean);
			return smsResultMap(true,msgId);
		} catch (APIConnectionException e) {
            LOG.error("网络连接失败，请稍后再试! ", e);
            return smsResultMap(false,"网络连接失败，请稍后再试! ");
        } catch (APIRequestException e) {
            LOG.error("极光服务器相应错误，请查看并修复! ", e);
            LOG.info("HTTP状态: " + e.getStatus());
            LOG.info("Error消息: " + e.getMessage());
            return smsResultMap(false,"服务器相应错误，请查看并修复! ");
        }
    }
    
    public static String SendValidSMSCode(String mobile, String messageId ,String validCode) {
    	SMSClient client = new SMSClient(MASTERSECRET, APPKEY);
		try {
			//验证：手机号与验证码之间的关系
			SmsVerCodeManagerBean bean = SmsVerCodeManager.getInstance().getVerCode(mobile);
			if(null==bean) {
				return "false"; 
			}
			if(!bean.getMsgId().equals(messageId)) {
				return "false";
			}
			ValidSMSResult res = client.sendValidSMSCode(messageId,validCode);
			if("true".equals(JSONObject.parseObject(res.toString()).getString("is_valid"))) {
				SmsVerCodeManager.getInstance().removeVerCode(mobile);
			}
			SmsVerCodeManager.getInstance().removeVerCode(mobile);
			return  JSONObject.parseObject(res.toString()).getString("is_valid"); 
		} catch (APIConnectionException e) {
            LOG.error("网络连接失败，请稍后再试! ", e);
            return "false";
        } catch (APIRequestException e) {
            LOG.error("极光服务器相应错误，请查看并修复!  ", e);
            LOG.info("HTTP状态: " + e.getStatus());
            LOG.info("Error消息: " + e.getMessage());
            return JSONObject.parseObject(e.getMessage()).getString("is_valid"); 
        }
	}
    
    
    public static Map<String,Object> notificationSMS(String mobile ,Integer templateId,Map<String,String> map) {
    	SMSClient client = new SMSClient(MASTERSECRET,APPKEY);
    	SMSPayload payload = SMSPayload.newBuilder()
				.setMobildNumber(mobile)
				.setTempId(templateId).setTempPara(map)
				.build();
		try {
			//清理过期与跨天数据
    		clear();
    		//检测未过期短信缓存中是否有本手机号的信息，如果有则更改信息(为保证数据正确性，重新进行数据的循环)
//    		SmsVerCodeManagerBean smsBean = null; 
//    		for (SmsVerCodeManagerBean bean : SmsVerCodeManager.getInstance().getAllVerCode()) {
//    			if(bean.getMobile().equals(mobile)) {
//    				smsBean = bean;
//    			}
//			}
    		//不存在则new一个新类
//    		if(null==smsBean) {
//    			smsBean = new SmsVerCodeManagerBean(); 
//    		}
    		//检测是否达到了每天最大发送是数量
//			if(smsBean.getSendCount()>smsBean.getSendMaxCount()) {
//				//不可再发送，给前台提示已到当日最大发送限制
//				return smsResultMap(false,"您已超过当日短信发送的最大限制");
//			}
    		SendSMSResult res = client.sendTemplateSMS(payload);
			String msgId = JSONObject.parseObject(res.toString()).getString("msg_id"); 
//			smsBean.setMobile(mobile);
//			smsBean.setMsgId(msgId);
//			smsBean.setSendCount(smsBean.getSendCount()+1);
//			smsBean.setSendDateTime(DateConvert.formatDateToString(new Date(), DateStyle.YYYY_MM_DD_HH_MM_SS));
//			SmsVerCodeManager.getInstance().addVerCode(mobile, null);
			return smsResultMap(true,msgId);
		} catch (APIConnectionException e) {
            LOG.error("网络连接失败，请稍后再试! ", e);
            return smsResultMap(false,"网络连接失败，请稍后再试! ");
        } catch (APIRequestException e) {
            LOG.error("极光服务器相应错误，请查看并修复!  ", e);
            LOG.info("HTTP状态: " + e.getStatus());
            LOG.info("Error消息: " + e.getMessage());
            return smsResultMap(false,"服务器相应错误，请查看并修复! ");
        }
	}
    /**
     * 功能说明：短信过期及款天内存数据的清理
     * 修改说明：
     * @author 吴兆强
     * @date 2018年1月26日 上午8:54:21
     */
    private static void clear() {
		//获取内存中所存储的所有验证码信息，检测过期验证码，并删除之
		SmsVerCodeManager smsManager = SmsVerCodeManager.getInstance();
		Collection<SmsVerCodeManagerBean> smsVerCodeList =  smsManager.getAllVerCode();
		for (SmsVerCodeManagerBean bean : smsVerCodeList) {
			//发送时间
			Date sendDateTime = DateConvert.formatStringToDate(bean.getSendDateTime(), DateStyle.YYYY_MM_DD_HH_MM_SS);
			Date sendDate = DateConvert.formatDateToDate(sendDateTime, DateStyle.YYYY_MM_DD);
			//失效时间
			Date invalidDateTime = DateConvert.addMinute(sendDateTime, 3);
			//当前时间
			Date currentDateTime = DateConvert.formatDateToDate(new Date(), DateStyle.YYYY_MM_DD_HH_MM_SS);
			Date currentDate = DateConvert.formatDateToDate(currentDateTime, DateStyle.YYYY_MM_DD);
			//清理跨天的数据（清理非当日数据）
			int noCurrentInt = currentDate.compareTo(sendDate);
			if(noCurrentInt!=0) {
				smsManager.removeVerCode(bean.getMobile());
			}
			//查看是否过期
			int compareInt = DateConvert.compare(currentDateTime, invalidDateTime, DateStyle.YYYY_MM_DD_HH_MM_SS);
			if(compareInt>0) {
				smsManager.removeVerCode(bean.getMobile());
			}
		}
    }
    
    /**
     * 功能说明：短信返回数据
     * 修改说明：
     * @author 吴兆强
     * @date 2018年1月25日 下午1:46:38
     * @param flag
     * @param msg
     * @return
     */
    private static Map<String,Object> smsResultMap(boolean flag, String msg){
    	Map<String,Object> map = new HashMap<String, Object>();
    	map.put("flag", flag);
    	map.put("msg", msg);
		return map;
    }
}
